package bg.cinema_system.beans;

import java.sql.SQLException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import bg.cinema_system.service.UserTicketsService;
import bg.cinema_system.utils.Constants;

@ManagedBean(name = "util")
@RequestScoped
public class UtilBean {

	public String ticketsInfo() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
		int userRole = (Integer) session.getAttribute("userRole");

		// Check if you are from the staff
		if (userRole == 2 || userRole == 3) {
			return "staff_tickets";
		} else {
			return "user_tickets";
		}
	}

	public String buyTicket() throws SQLException {
		String user_id = FacesContext.getCurrentInstance().getExternalContext()
				.getRequestParameterMap().get("user_id");

		String projection_id = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap()
				.get("projection_id");

		boolean checkUpdate;

		try {
			checkUpdate = UserTicketsService.buyTicket(
					Integer.parseInt(user_id), Integer.parseInt(projection_id),
					Constants.TICKET_PRICE);
			System.out.println(user_id + " " + projection_id);
		} catch (NumberFormatException e) {
			checkUpdate = false;
		} catch (SQLException e) {
			checkUpdate = false;
		}

		if (!checkUpdate) {
			return "";
		} else {
			return "updated";
		}
	}

	public String getUsername() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);

		int user_id = (Integer) session.getAttribute("userId");
		String username;
		try {
			username = UserTicketsService.getUsername(user_id);
		} catch (SQLException e) {
			username = "";
		}

		return username;
	}

	public String getRole() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);

		int userRole = (Integer) session.getAttribute("userRole");

		if (userRole == 2) {
			return "staff";
		} else if (userRole == 3) {
			return "admin";
		} else {
			return "";
		}
	}
}
